package com.ljs.module.util;

import com.ljs.module.entity.ConfigProperties;
import com.spreada.utils.chinese.ZHConverter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 翻译转化相关工具类
 * Created by lijunsai on 2021/07/09
 */
public class ConvertrUtil {

    public static Map<String, String> systemConfigItem = new HashMap<>();

    static {
        // 系统配置项中自带的一些 直接初始化
        systemConfigItem.put("公共设置","${Publicsettings}");
        systemConfigItem.put("邮件设置","${Messagesettings}");
        systemConfigItem.put("文件导出设置","${Exportreportsettings}");
        systemConfigItem.put("上传文件设置","${UploadFileSetting}");
        systemConfigItem.put("图形设置","${Graphicsettings}");
        systemConfigItem.put("服务器地址","${ServerAddress}");
        systemConfigItem.put("用户管理","${Usermanagementsettings}");
        systemConfigItem.put("数据集","${Querysettings}");
        systemConfigItem.put("文件缓存设置","${FileCacheSettings}");
        systemConfigItem.put("自助仪表盘","${Smartbixdashboard}");
        systemConfigItem.put("灵活分析|即席查询","${Flexibleanalysissettings}");
        systemConfigItem.put("字体|背景颜色设置","${Font}|${Backgroundcolor}${Set}");
        systemConfigItem.put("多维分析","${Multidimensionalanalysissettings}");
        systemConfigItem.put("缓存","${Poolsettings}");
        systemConfigItem.put("业务数据缓冲池","${Businessdatainthebufferpool}");
        systemConfigItem.put("数据集定义对象池","${TheDataSetdefinestheobjectpool}");
        systemConfigItem.put("参数缓存","${ParameterAutomaticcaching}");
        systemConfigItem.put("电子表格","${SpreadsheetReport}");
//        systemConfigItem.put("即席查询",""); // 没找到
        systemConfigItem.put("电子表格","${SpreadsheetReportSettings}");
        systemConfigItem.put("清单表","${SpreadsheetReportListReport}");
        systemConfigItem.put("水印","${Watermark}");
        systemConfigItem.put("文件回写位置设置","${BackWriteFileSettings}");
        systemConfigItem.put("透视分析","${InsightSettings}");
//        systemConfigItem.put("引擎设置",""); // 没找到
//        systemConfigItem.put("移动端",""); // 没找到
//        systemConfigItem.put("移动端设置",""); // 没找到
//        systemConfigItem.put("离线设置",""); // 没找到
    }

    public static String judgeSpecialZh(String zh){
        Pattern p = Pattern.compile("\\$\\{(.*?)}");
        Matcher matcher = p.matcher(zh);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    /**
     * 繁体转简体
     * @param str 繁体
     * @return 简体
     */
    public static String complexToSimple(String str) {
        return ZHConverter.convert(str, ZHConverter.SIMPLIFIED);
    }

    /**
     * 简体转繁体
     * @param str 简体
     * @return 繁体
     */
    public static String simpleToComplex(String str) {
        return ZHConverter.convert(str, ZHConverter.TRADITIONAL);
    }


    /**
     * 中文转英文
     * @param zh 中文
     * @return 英文
     */
    public static String zhToEn(String zh, ConfigProperties configProperties){
        return translate("zh-CN","en",zh, configProperties);
    }

    /**
     * 翻译接口
     * @param langFrom 原类型
     * @param langTo 需要翻译的类型
     * @param word 单词
     * @return 翻译结果
     */
    public static String translate(String langFrom, String langTo,
                            String word, ConfigProperties configProperties){
        if (configProperties.isNotInternet()) {
            return "translate error " + UUID.randomUUID().toString().replaceAll("-", "_");
        }
        try {
            String url = "https://translate.googleapis.com/translate_a/single?" +
                    "client=gtx&" +
                    "sl=" + langFrom +
                    "&tl=" + langTo +
                    "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            String s = response.toString();
            String sub1 = s.substring(s.indexOf("\"") + 1);
            in.close();
            return sub1.substring(0, sub1.indexOf("\""));
        } catch (Exception e) {
            System.err.println("翻译出错");
            return "translate error " + UUID.randomUUID().toString().replaceAll("-", "_");
        }

    }

    /**
     * 中文转unicode
     * @param gbString 需要转的字符串
     * @return unicode
     */
    public static String encodeUnicode(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }

    /**
     * unicode 转中文
     * @param dataStr 需要转的字符串
     * @return 转换后的
     */
    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

    public static String getConfig (String name) {
        return systemConfigItem.get(name);
    }

}
